#include "threadPool.h"
#include "dircmd.h"
#include "dirStack.h"

int mycd(dirStack_t *pStack, char *arg, char *ret) {
    //拆分arg
    char buf[1024] = {0};
    visitStack(pStack, buf);
    if(access(buf, F_OK)) {
        return -1;
    }
    char *sockPath = strtok(arg, "/");
    while(1) {
        if(!sockPath) {
            break;
        }
        if(strcmp(sockPath, ".") != 0 && strcmp(sockPath, "..") != 0) {
            enStack(pStack, sockPath);
        }
        if(strcmp(sockPath, "..") == 0) {
            deStack(pStack);
        }
        sockPath = strtok(NULL, "/");
    }

    if(strcmp(ret, "") == 0) {
        memcpy(ret, "/", 1);
    }

    return 0;
}

int myls(dirStack_t *pStack, char *dirPath, char *ret) {
    /* char rootPath[] = "/home/lxy/cpp53/netdisk/server/zs"; */
    char rootPath[1024];
    visitStack(pStack, rootPath);
    // 使用字符串连接函数将dirPath拼接到rootPath后面
    strcat(rootPath, dirPath);
    /* if(strcmp(dirPath, "") == 0) { */
    /*     memcpy(dirPath, ".", 1); */
    /* } */
    printf("myls rootPath = %s\n", rootPath);
    DIR *pdir = opendir(rootPath);
    struct dirent *pdirent;

    // 打开目录
    if (pdir == NULL) {
        perror("opendir");
        return -1;
    }


    // 读取目录项
    while ((pdirent = readdir(pdir))) {
        strcat(ret, pdirent->d_name);
        strcat(ret, " ");
    }

    ret[strlen(ret) - 1] = '\0';

    printf("ret = %s\n", ret);
    // 关闭目录
    closedir(pdir);
    return 0;
}

int mypwd(dirStack_t *taskStack, char *ret) {
    char buf[1024];
    node_t *pCur = taskStack->pFront;

    strcpy(ret, ""); // 初始化ret为空字符串

    while (pCur->pNext) {
        strcpy(buf, "/");
        strcat(buf, pCur->data);
        strcat(buf, ret);
        strcpy(ret, buf);
        pCur = pCur->pNext;
    }

    // 去除末尾多余的斜杠
    if (strlen(ret) > 0 && ret[strlen(ret) - 1] == '/') {
        ret[strlen(ret) - 1] = '\0';
    }
    
    if(strcmp(ret, "") == 0) {
        memcpy(ret, "/", 1);
    }

    return 0;
}
